package com.chen.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.security.mapper.PermissionsMapper;
import com.chen.security.mapper.UsersMapper;
import com.chen.security.pojo.Permissions;
import com.chen.security.pojo.Users;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private PermissionsMapper permissionsMapper;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = usersMapper.selectOne(wrapper);
        if(users == null)
            throw new UsernameNotFoundException("用户不存在");

        String encode = passwordEncoder.encode(users.getPassword());
        // 查询用户权限
        List<Permissions> permissionsList = permissionsMapper.selectPermissions(users.getId());
        List<String> permissions = new ArrayList<>();
        permissionsList.forEach(item -> permissions.add(item.getCode()));

        UserDetails userDetails = User.withUsername(users.getUsername()).password(encode).authorities(permissions.toArray(new String[permissions.size()])).build();
        System.out.println(userDetails);
        return userDetails;
    }

    public void getAuthentication(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);
    }
}
